<template>
  <ContentCard :padding="0">
    <template #header>
      <pageHeaderNew
        title="编辑详情"
        :breadCrumb="['人事', '人事管理', '编辑详情']"
        :showBack="true"
      ></pageHeaderNew>
    </template>
    <div>
      <div
        class="subDetail"
        v-for="item in data.data"
        :key="(item.subCode as string)"
      >
        <div class="head">
          <div class="sub-title">
            <p class="icon"></p>
            {{ item.cnName }}
          </div>
          <!-- <div class="setting" @click="change">设置</div> -->
        </div>
        <a-divider></a-divider>
        <div style="padding: 0 20px; margin: auto">
          <a-form ref="HumanForm" :model="item.controlModel" autoLabelWidth>
            <a-row :gutter="100">
              <template v-for="(ele, index) in item?.controlModel" :key="index">
                <a-col :span="ele.span ? ele.span : 12">
                  <FormItem
                    :disabled="ele?.disabled"
                    :componentType="(ele?.ctlComponentType as string)"
                    :props="(ele?.props as any)"
                    :name="(ele?.ctlCnName as string)"
                    :required="(ele?.ctlRequired as any)"
                    v-model:values="ele.ctlValue"
                    :code="(ele?.ctlCode as any)"
                    :selectOptions="ele.selectOptions"
                    :data="ele"
                  />
                </a-col>
              </template>
            </a-row>
          </a-form>
        </div>
      </div>
    </div>
    <!-- <a-affix :offsetBottom="0">
      <div class="btn">
        <a-button @click="router.back()">返回</a-button>
        <a-button type="primary" @click="submit">保存</a-button>
      </div>
    </a-affix> -->
    <footer>
      <a-button
        class="btn"
        style="
          margin-right: 20px;
          border: 1px rgba(242, 242, 242, 1) solid;
          background-color: #fff;
        "
        @click="$router.go(-1)"
      >
        返回
      </a-button>
      <a-button class="btn" type="primary" @click="submit">保存</a-button>
    </footer>
  </ContentCard>
</template>
<script lang="ts" setup>
/**
 * 1、设置模板：根据业务code获取总集的业务，业务下的控件都是默认控件
 * 2、根据需求增加子集和控件，此种控件仅做数据记录，没有其他功能
 * 3、保存生成模板，页面调用此模板填写数据保存
 *
 */
import { isJSON } from '@/utils/isType';
import {
  GetOnboarding,
  EditOnboarding,
  GetManual
} from '@/apis/management/personnel/baseSetting/TransactionSetting';
import {
  GetStaff,
  GetStaffDetails,
  PutNewStaff
} from '@/apis/management/personnel/baseSetting/TransactionSetting';

import FormItem from '@/components/DynamicFormsNew/RenderingForm/FormItem/index.vue';
import { useRouter } from 'vue-router';
import {
  GetlistData,
  GetByorg,
  GetByid
} from '@/apis/management/personnel/baseSetting/TransactionSetting';
import useControlFormStore from '@/store/controlForm';
const controlFormStore = useControlFormStore();
controlFormStore.fieldNames.labelName = 'ctlCnName';
controlFormStore.fieldNames.componentType = 'ctlComponentType';
controlFormStore.fieldNames.valueName = 'ctlValue';
interface idsType {
  corporation: number;
  section: number;
  Position: number;
}
const router = useRouter();
const page = reactive({ page: 1, size: 10 });
console.log(router.currentRoute.value.query.id);
const { node, id } = router.currentRoute.value.query;
// const node = router.currentRoute.value.query.node
// const id = router.currentRoute.value.query.id
const ids: idsType = { corporation: 0, section: 0, Position: 0 };
const data: any = reactive({ data: [] });
const init = async () => {
  // TODO: 工号待完成
  const manual = 1; // (await GetManual()).status;
  const resData: any = await GetStaffDetails({ id: Number(id) });
  data.data = resData.useTemplate.collectionModel || [];
  templateData.personnelList[0].personnelInstitutionListModel.id = resData.id;

  data.data.forEach((ele: any) => {
    ele.controlModel?.forEach(async (item: any) => {
      let ctlValue = item?.ctlValue?.ctlValue;
      item.ctlValue = ctlValue;
      item.props = JSON.parse(item.props);
      if (item?.ctlFieldName === 'jobNumber' && manual === 2) {
        item.props.placeholder = '自动生成工号';
        // item.props = JSON.stringify(item.props);
        item.disabled = true;
        item.required = 2;
      }
      // console.log(item.ctlCode, item.ctlCnName);

      // 获取公司ID
      if (item.ctlCode === 'CA8ABCC1480744557B3014C3454465A7E') {
        ids.corporation = +ctlValue;
      }
      // 获取部门ID
      if (item.ctlCode === 'CED44AC9966904CD1AB546D309903727C') {
        ids.section = +ctlValue;
      }
      // 获取职位ID
      if (item.ctlCode === 'C7341027925C943708F3AEF98703ECC47') {
        ids.Position = +ctlValue;
      }
      // if (ctlValue) {
      //   if (isJSON(item.controlValue)) {
      //     item.ctlValue.ctlValue = JSON.parse(ctlValue);
      //   } else if (!isNaN(+ctlValue)) {
      //     item.ctlValue.ctlValue = Number(ctlValue);
      //   }
      // }
    });
  });

  let idaaa = 0;
  data.data.forEach((ele: any) => {
    ele.controlModel.forEach(async (item: any) => {
      // let ctlValue = item.ctlValue.ctlValue;
      if (item.ctlCode === 'CED44AC9966904CD1AB546D309903727C') {
        item.selectOptions = await GetlistData({
          type: 2,
          id: ids.corporation
        });
        console.log(1, item.selectOptions);
      }
      // if (item.ctlCode === 'C7341027925C943708F3AEF98703ECC47') {
      //   item.selectOptions = await GetByorg({
      //     id: ids.section
      //   });
      //   console.log(2, item.selectOptions);
      // }
      // if (item.ctlCode === 'C0DA2ECD7408E49FDB76933475EB028DE') {
      //   item.selectOptions = await GetByid({
      //     id: ids.Position
      //   });
      // }
      // 公司和部门下拉联动
      if (item.ctlCode === 'CA8ABCC1480744557B3014C3454465A7E') {
        idaaa = item.ctlValue;
      } else if (item.ctlCode === 'CED44AC9966904CD1AB546D309903727C') {
        let data = await GetlistData({ type: 2, id: idaaa });
        setTimeout(() => {
          item.selectOptions = data;
        }, 100);
      }
    });
  });
};
const disabled = ref(true);
const change = () => [(disabled.value = !disabled.value)];
init();
const templateData: any = {
  personnelList: [
    {
      personnelInstitutionListModel: {},
      personnelTemplateCtlValue: []
    }
  ]
};
const HumanForm = ref();

/**
 * 验证所有表单
 */
const validate = async () => {
  let flag = true;
  for (let index = HumanForm.value.length; index > 0; index--) {
    if (await HumanForm.value[index - 1].validate()) {
      //验证不通过
      flag = false;
    }
  }
  return flag;
};
const submit = async () => {
  if (!(await validate())) return;
  data.data.forEach((item: any) => {
    let ctlItem: any = {};
    item.controlModel?.forEach((ele: any) => {
      ctlItem.ctlValue = ele.ctlValue ? `${ele.ctlValue}` : void 0;
      ctlItem.id = ele.ctlValue.id;
      templateData.personnelList[0].personnelTemplateCtlValue.push({
        ...ctlItem
      });
      switch (ele.ctlCode) {
        case 'C62B8DC31189847E0972B5D8F721404B1': // 姓名
          templateData.personnelList[0].personnelInstitutionListModel.name =
            ctlItem.ctlValue;
          templateData.personnelList[0].personnelInstitutionListModel.templateUseId =
            ctlItem.templateId;
          break;
        case 'C3384BE6E60C341D68B8180DA04A1C4E1': // 手机号
          templateData.personnelList[0].personnelInstitutionListModel.mobile =
            ctlItem.ctlValue;
          break;
        case 'CDA91C3B660FC46CBA7978E7031672229': // 邮箱
          templateData.personnelList[0].personnelInstitutionListModel.email =
            ctlItem.ctlValue;
          break;
        case 'C7341027925C943708F3AEF98703ECC47': // 职位
          if (ctlItem.ctlValue) {
            templateData.personnelList[0].personnelInstitutionListModel.positionId =
              Number(ctlItem.ctlValue);
          }
          break;
        case 'CA8ABCC1480744557B3014C3454465A7E': // 公司
          if (ctlItem.ctlValue) {
            templateData.personnelList[0].personnelInstitutionListModel.companyId =
              +ctlItem.ctlValue;
          }
          break;
        case 'CED44AC9966904CD1AB546D309903727C': // 部门
          templateData.personnelList[0].personnelInstitutionListModel.departmentId =
            +ctlItem.ctlValue;
          break;
        default:
          break;
      }
    });
  });
  console.log('templateData', templateData);

  await PutNewStaff(templateData);
  router.back();
};
</script>
<style lang="less" scoped>
.subDetail {
  .head {
    box-sizing: border-box;
    border-radius: 4px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-sizing: border-box;
    padding: 0 10px;
    // background-color: #e8f0ff;
    margin: 20px 0;
    .sub-title {
      display: flex;
      align-items: center;
      .icon {
        border-radius: 4px;
        width: 6px;
        height: 70%;
        background-color: #3d7eff;
        height: 20px;
        padding: 0;
        margin: 3px 0;
        margin-right: 10px;
      }
    }
    .setting {
      color: #3d7eff;
      cursor: pointer;
    }
  }
}
footer {
  height: 60px;
  width: calc(100% - 100px);
  background-color: #fff;
  box-shadow: 1px -1px 10px 0 #cacaca;
  position: fixed;
  bottom: 0;
  left: 10%;
  display: flex;
  justify-content: center;
  align-items: center;

  .btn {
    width: 120px;
    height: 40px;
    border-radius: 5px;
  }
}
:deep(.arco-btn) {
  margin-right: 20px;
  width: 120px;
}
</style>
